package com.wwt.blog.imp;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wwt.blog.mapper.*;
import com.wwt.blog.pojo.*;
import com.wwt.blog.service.*;
import com.wwt.blog.utils.UserThreadLocal;
import com.wwt.blog.vo.*;
import com.wwt.blog.vo.param.ArticleParam;
import com.wwt.blog.vo.param.PageParams;
import org.apache.commons.collections.CollectionUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleServiceImp implements ArticleService {
    //@Autowired
    @Resource
    ArticleMapper articleMapper;
    @Resource
    TagService tagService;
    @Resource
    SysUserService sysUserService;
    @Resource
    ThreadService threadService;
    @Override
    public Result listArticles(PageParams pageParams) {
        /**
         * Description:分页查询
         */
        Page<Article> page=new Page<>(pageParams.getPage(), pageParams.getPageSize()); //参数存放当前查询的页数和数量
//        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<Article>();查询条件
        IPage<Article> iPage = articleMapper.listArticles(page,pageParams.getTagId(),
                                                          pageParams.getCategoryId(),
                                                          pageParams.getYear(),
                                                           pageParams.getMonth());
        List<Article> records = iPage.getRecords();

        /**
         * 重构  用mybatis自定义语句实现
         */
        /*//某分类下的文章
        if(pageParams.getCategoryId()!=null){
            queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
        }
        //添加某标签下的文章
        if (pageParams.getTagId()!=null){
            //先查出该标签下有哪些文章
            LambdaQueryWrapper<ArticleTag> wrapper = new LambdaQueryWrapper();
            wrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
            List<ArticleTag> articleTags = articleTagMapper.selectList(wrapper);
            //抽取这些对象的文章ID作为所有文章的查询条件
            ArrayList<Long> list = new ArrayList<>();
            for (ArticleTag tag :articleTags)
                list.add(tag.getArticleId());
            queryWrapper.in(Article::getId,list);
        }

        queryWrapper.     //排序规则  时间倒序+权重(置顶）
                orderByAsc(Article::getWeight)
                .orderByDesc(Article::getCreateDate);
        Page<Article> page1 = articleMapper.selectPage(page, queryWrapper);
        //selectPage方法返回地是一个IPage类型的对象
        List<Article> records = page1.getRecords(); //此时得到了Article样式的数据，并非展示在页面上的数据*/

        List<ArticleVo> articleVos = copyList(records,true,true);
        return Result.result_success(articleVos);

    }

    @Override
    //获取浏览量前5的文章为最热文章
    public List<ArticleVo> getHotArticles() {
        List<Article> hotArticles = articleMapper.getHotArticles();
        List<ArticleVo> list = copyList(hotArticles, false, false);
        return list;
    }

    //获取时间前5的文章为最新文章
    @Override
    public List<ArticleVo> getNewArticles(int limit) {
        /*QueryWrapper<Article> wrapper=new QueryWrapper();
        String sql="select id,title from ms_article limit order by create_date desc #{limit}";
        wrapper.inSql("create_date",sql);*/
        List<Article> articles = articleMapper.getNewArticles(limit);
        return copyList(articles,false,false);
    }

    //文章归档的实现
    @Override
    public Result getListArchives() {
        List<dos> listArchives = articleMapper.getListArchives();
        return Result.result_success(listArchives);
    }
    //文章详情
    @Override
    public Result getArticleBodyById(Long articleId) {
        Article article = articleMapper.selectById(articleId);
        ArticleVo articleVo = copy(article, true, true, true, true);
        //返回文章之前增加浏览数 使用线程池
        threadService.upDateViewCount(article,articleMapper);
        return Result.result_success(articleVo);
    }

    @Autowired
    ArticleTagMapper articleTagMapper ;
    //发布文章
    @Override
    public Result articlePublish(ArticleParam articleParam) {
        //取出当前用户
        SysUser user = UserThreadLocal.get();

        //设置文章属性
        Article article = new Article();
        article.setAuthorId(user.getId());
        article.setCreateDate(System.currentTimeMillis());
        article.setViewCounts(0);

        //修改了之前的类型
        article.setCategoryId(Integer.valueOf(articleParam.getCategory().getId()) );
        article.setCommentCounts(0);
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        article.setWeight(0);
        //先插入 取得下面需要的articleTag  后面再更新
        article.setBodyId(-1L);
        articleMapper.insert(article);
        //设置tags
        List<TagVo> tags = articleParam.getTags();
        if (!CollectionUtils.isEmpty(tags)){
            for (TagVo tagVo: tags) {
                ArticleTag tag = new ArticleTag();
                tag.setTagId(Integer.valueOf(tagVo.getId()));
                tag.setArticleId(article.getId());
                articleTagMapper.insert(tag);
            }
        }
        //设置articleBody
        ArticleBody body = new ArticleBody();
        body.setArticleId(article.getId());
        body.setContent(articleParam.getBody().getContent());
        body.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(body);
        article.setBodyId(body.getId());
        articleMapper.updateById(article);

        ArticleVo vo = new ArticleVo();
        vo.setId(article.getId().toString());
        return Result.result_success(vo);
    }

    //将于数据库对应的Article类型的数据转化于页面展示的ArticleVo类型的数据
    public List<ArticleVo> copyList(List<Article> records,Boolean hasTag,Boolean hasAuthor){
        List<ArticleVo> articleVoList=new ArrayList<>();
        for (Article article:records) {
            articleVoList.add(copy(article,true,true));
        }
        return articleVoList;
    }

    public ArticleVo copy(Article article,Boolean hasTag,Boolean hasAuthor){
        ArticleVo articleVo=new ArticleVo();
        //BeanUtils的copyPro方法实现相同属性复制
        BeanUtils.copyProperties(article,articleVo);
        //改变ID类型后无法自动注入
        articleVo.setId(String.valueOf(article.getId()));
        //无法自动注入的时间  调用函数来转化
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:SS"));
        //标签信息
        if(hasTag){
           List<TagVo> tagList=new ArrayList<>();  //一个文章可能有多个标签
            tagList=tagService.findTagsByArticleId(article.getId());
            articleVo.setTags(tagList);
        }
        //添加作者信息
        if(hasAuthor){
           articleVo.setAuthor(sysUserService.getAuthorByAuthorId(article.getAuthorId()).getNickname());
        }
        return articleVo;
    }

    @Autowired
    ArticleBodyMapper articleBodyMapper;
    @Autowired
    CategoryService categoryService;
    public ArticleVo copy(Article article,Boolean hasTag,Boolean hasAuthor,Boolean hasBody,Boolean hasCategory){
        //返回不完整的文章
        ArticleVo vo = copy(article, hasTag, hasAuthor);
        //添加文章体
        if(hasBody){
            Long id=article.getBodyId();
            ArticleBody body =articleBodyMapper.selectById(id);
            ArticleBodyVo bodyVo=new ArticleBodyVo();
            BeanUtils.copyProperties(body,bodyVo);
            vo.setBody(bodyVo);
        }
        //添加分类信息
        if(hasCategory){
            int id = article.getCategoryId();
            Category category = categoryService.getCategory(id);
            CategoryVo categoryVo=new CategoryVo();
            BeanUtils.copyProperties(category,categoryVo);
            vo.setCategory(categoryVo);
        }
        return vo;
    }
}
